/**
 * 
 */
package us.gaaoc.framework.webapp.backingbeans.attorney;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import us.gaaoc.framework.model.CaseRecord;
import us.gaaoc.framework.model.Documents;
import us.gaaoc.framework.model.Person;
import us.gaaoc.framework.webapp.backingbeans.BaseBackingBean;
import us.gaaoc.framework.webapp.util.Messages;

/**
 * @author Sukahda Tapshalkar
 * Apr 19, 2007
 *
 */
@SuppressWarnings("unchecked")
public class RejectFilingPage extends BaseBackingBean {
	
	/** Generated Serial Version UID */
	private static final long serialVersionUID = 5253549032007264564L;

	/**
	 * Properties
	 */
	private String rejectionReason;

	private UIInput rejectionReasonInput;

	private FacesMessage message; 
	
	private Date courtDate;
	
	private boolean secureReject;
	
	public boolean isSecureReject() {
		return secureReject;
	}

	public void setSecureReject(boolean secureReject) {
		this.secureReject = secureReject;
	}

	/**
	 * Constructor
	 *
	 */
	public RejectFilingPage() {
		
	}

	/**
	 * @return the courtDate
	 */
	public Date getCourtDate() {
		return courtDate;
	}

	/**
	 * @param courtDate the courtDate to set
	 */
	public void setCourtDate(Date courtDate) {
		this.courtDate = courtDate;
	}

	/**
	 * @return the message
	 */
	public FacesMessage getMessage() {
		return message;
	}

	/**
	 * @param message the message to set
	 */
	public void setMessage(FacesMessage message) {
		this.message = message;
	}

	/**
	 * @return the rejectionReason
	 */
	public String getRejectionReason() {
		return rejectionReason;
	}

	/**
	 * @param rejectionReason the rejectionReason to set
	 */
	public void setRejectionReason(String rejectionReason) {
		this.rejectionReason = rejectionReason;
	}

	/**
	 * @return the rejectionReasonInput
	 */
	public UIInput getRejectionReasonInput() {
		return rejectionReasonInput;
	}

	/**
	 * @param rejectionReasonInput the rejectionReasonInput to set
	 */
	public void setRejectionReasonInput(UIInput rejectionReasonInput) {
		this.rejectionReasonInput = rejectionReasonInput;
	}

	/**
	 * This method resets the rejection reason input field
	 * @return String
	 */
	public String reset(){
		this.getRejectionReasonInput().setSubmittedValue(null);
		return "stay";
	}
	
	/**
	 * This mathod navigates user to the brevious page
	 * @return String
	 */
	public String back(){
		Map sessionMap = this.getFacesContext().getExternalContext()
		.getSessionMap();
		sessionMap.remove("caseRecord");
		return "gotoCaseDetailsPage";
	}
	/**
	 * This method gets called when the clerk confirm to reject
	 * the case record
	 * @return String
	 */
	public void rejectFiling() {
		Map sessionMap = this.getFacesContext().getExternalContext()
				.getSessionMap();
		//CaseRecord caseRecord = (CaseRecord)sessionMap.get("caseRecord");
		String courtUuid = (String) sessionMap.get("courtUuid");
		Person person = (Person) this.getFacesContext()
		.getExternalContext().getSessionMap().get("person");
		
		String caseRecordUuid = (String) sessionMap.get("caseUuid");
		//update in the mysql database
		// CaseRecordStatus = rejectedByAttorney (8)
		this.getModelFacade().updateRejectedCaseRecord(caseRecordUuid, this.getRejectionReason(),8, courtUuid);
		//CaseRecordEventType = Filing rejected by Attorney (8)
		this.getModelFacade().addCaseRecordHistory(caseRecordUuid, 8, person, courtUuid,"no comments");
		
		if (secureReject == true) {
			// Delete Documents signed by Attorney and Clerk if Secure Reject
			// box is checked
			List<Documents> listOfDoc = new ArrayList<Documents>();
			listOfDoc = this.getModelFacade().findDocumentsByCaseUuid(
					caseRecordUuid);

			for (Documents d : listOfDoc) {

				/*
				 * Check if the document is signed by Attorney(status=11) or
				 * Clerk(status=8), delete it if so.
				 */

				if (d.getStatus().getCode() == 8
						|| d.getStatus().getCode() == 11) {
					this.getModelFacade().deleteDocument(d);
				}
			}

			//
			// commit the transaction
		//	HibernatePhaseListener.getSessionFactory().getCurrentSession()
			//		.getTransaction().commit();
		} 
		
	}

	/**
	 * This method validates the rejected reason typed by user
	 * @param context
	 * @param component
	 * @param value
	 * @throws ValidatorException
	 * @throws Exception
	 */
	public void validateReason(FacesContext context, UIComponent component,
			Object value) throws ValidatorException, Exception {
		String rejectionReason = (String) value;
		if (!isValidReason(rejectionReason)) {
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(message);
		}
	}

	/**
	 * Helper method to validate the rejection reason
	 * @param value
	 * @return
	 * @throws Exception
	 */
	protected boolean isValidReason(String value) throws Exception {
		boolean isValid = true;
		char[] charArray = value.toCharArray();
		
		if(value.length() > 100) // 100 character limit is hard-coded in the database schema
		{
			isValid = false;
			message = Messages.getMessage(
					"us.gaaoc.framework.webapp.util.errorMessage",
					"tooLargeRejectionReason", new Object[] { value.length()-100 });
			message.setDetail(message.getDetail());
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
		}else{
		
			for (char c : charArray) {
				if (Character.isDigit(c) || Character.isLetter(c)
						|| Character.isSpaceChar(c)) {
				} else {
					String s = new Character(c).toString();
					if (s.equals("!") || s.equals(",") || s.equals(";")
							|| s.equals(".") || s.equals("'") || s.equals("\"")
							|| s.equals("%") || s.equals(":") || s.equals("(") || s.equals(")") 
							|| ((Integer.valueOf((int)c)) == 13)  // carriage return
							|| ((Integer.valueOf((int)c)) == 10)) // newline
					{} else {
						isValid = false;
						message = Messages.getMessage(
								"us.gaaoc.framework.webapp.util.errorMessage",
								"incorrectRejectionReason", new Object[] { value, s });
						message.setDetail(message.getDetail());
						message.setSeverity(FacesMessage.SEVERITY_ERROR);
						break;
					}
				}
			}
		}
		return isValid;
	}

}
